package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        只要访问后台是以/back/开始的都要判断是否已经登录
        String path = req.getServletPath();
        if (path.startsWith("/back/")) {
            String key = req.getParameter("loginName");
            String username = (String) req.getSession().getAttribute(key);
            if (username == null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", "error");
                resp.getWriter().println(jsonObject);
            } else {
                filterChain.doFilter(req, resp);//放行
            }
        } else {
            filterChain.doFilter(req, resp);//放行
        }

    }

    @Override
    public void destroy() {

    }
}
